package com.liyuci.core.thymeleaf.eleondialect.element;

import com.liyuci.core.helper.BlankHelper;
import com.liyuci.core.service.IService;
import com.liyuci.core.thymeleaf.eleondialect.BaseElementTagProcessor;
import com.liyuci.eleon.admin.dept.Dept;
import com.liyuci.eleon.admin.dept.DeptService;

import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.time.StopWatch;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Sort.Direction;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.spring4.context.SpringContextUtils;
import org.thymeleaf.templatemode.TemplateMode;

/**
 * select标签
 * @author liyuci
 * @date 2018-02-05 14:17:40
 */
@Slf4j
public class SelectElementTagProcessor extends BaseElementTagProcessor
{
	// 标签名
	private static final String ELEMENT_NAME = "select";

	public SelectElementTagProcessor(String dialectPrefix)
	{
		super(TemplateMode.HTML, 	// 此处理器将仅应用于HTML模式
				dialectPrefix, 		// 要应用于名称的匹配前缀
				ELEMENT_NAME, 		// 标签名称：匹配此名称的特定标签
				true, 				// 将标签前缀应用于标签名称
				null, 				// 无属性名称：将通过标签名称匹配
				false, 				// 没有要应用于属性名称的前缀
				PRECEDENCE); 		// 优先(内部方言自己的优先)
	}

	@Override
	protected void doProcess(ITemplateContext context, IProcessableElementTag tag, IElementTagStructureHandler structureHandler)
	{
		StopWatch watch = new StopWatch();
		watch.start();
		
		//基本属性
		final String id = getString(context, tag, "id");
		final String name = getString(context, tag, "name");
		final String value = getString(context, tag, "value");
		
		//扩展属性
		//final List<Dept> listDept2 = getList(context, tag, "listDept");
		//final List<String> listDeptId = getListByDelimiter(context, tag, "deptIds");
		
		/**
		* 获取应用程序上下文。
		*/
		ApplicationContext appCtx = SpringContextUtils.getApplicationContext(context);
		IService<Dept> service = appCtx.getBean(DeptService.class);
		List<Dept> listDept = service.listAll("name", Direction.ASC);
		
		StringBuilder html = new StringBuilder();
		html.append("<" + ELEMENT_NAME);
		html.append(getIdAndNameHtml(id, name));
		html.append(">");
		for(Dept dept : listDept)
		{
			html.append("<option value='"+ dept.getId() +"' ");
			if(BlankHelper.isNotBlank(value) && value.equals(dept.getId()))
			{
				html.append(" selected=true ");
			}
			html.append(">"+ dept.getName() +"</option>");
		}
		html.append("</"+ ELEMENT_NAME +">");
		
		//生成html信息
		generateHtml(context, structureHandler, html);
		watch.stop();
		log.info("[Select标签]耗时："+ watch.getTime() +"ms.");
	}
	
}
